/**
 * 上传素材图片并预览 
 * inputFileId	:	图片文件 
 * imageShowDiv	:	图片预览 
 * imageUrlId	:	图片UrlID
 * fileType		:	文件类型(0:其他文件; 1:用户头像; 2:设备; 3:广告素材; 4：数据报告; 5:公司资料; 6:效果监播)
 * materialType	:	文件类型(1:图片 2:视频 3:音频 4:网页 5:其他)
 */
function selectFile(inputFileId, imageShowDiv, imageUrlId, fileType, materialType) {
	
	//文件种类
	var suppotFormat = getFileSuffix(materialType);
	//校验文件合法性
	var fileObjs = document.getElementById(inputFileId);
	//文件集合
	var fileList = fileObjs.files;
	for (var i = 0; i < fileList.length; i++) {
		var fileName = fileList[i].name;
		//转换大小写
		var suffix = (fileName.substring(fileName.lastIndexOf(".")+1,fileName.length)).toLowerCase(); 
		var index = suppotFormat.indexOf(suffix);
		if (index == -1) {
			//文件格式错误提示
			$("#" + inputFileId).tips({
				side : 3,
				msg : '文件格式错误，支持的格式为：'+suppotFormat,
				bg : '#1abc9d',
				time : 5
			});
			// 清空文件路径
			fileObjs.outerHTML=fileObjs.outerHTML; 
			return false;
		}
	}
	
	createLoadingDiv();

	// 调用接口
	var url = "";
	var html = "";
	for (var i = 0; i < fileList.length; i++) {
		
		//请求参数
		var formdata = new FormData();
		formdata.append("dataFile", fileList[i]);
		formdata.append("fileType", fileType);
		
		$.ajax({
			type : 'POST',
			url : 'file/uploadFile',
			data : formdata,
			dataType : "json",
			async : false,
			cache : false,
			// 必须false才会自动加上正确的Content-Type
			contentType : false,
			// 必须false才会避开jQuery对formdata的默认处理,XMLHttpRequest会对 formdata进行正确的处理
			processData : false,
			beforeSend : function() {
				createLoadingDiv();
			},
			success : function(repsonse) {
				if (repsonse.code == 0) {
					// 获取返回路径
					url += repsonse.data.url+",";
					html += fillFileDiv(repsonse.data.url, materialType);
				}else {
					showAlert(repsonse.message);
					//关闭Loading
					closeLoadingDiv();
				}
			},
			error : function(data) {
				showAlert(fileList[i]+"上传失败!");
				//关闭Loading
				closeLoadingDiv();
			}
		});
	}

	if (url != "" && url.length > 0) {
		if (materialType == "1") {
			//图片预览
			var $imageShowDiv = document.getElementById(imageShowDiv);
			$imageShowDiv.innerHTML = html;
		}
		//设置文件URL
		$("#" + imageUrlId).val(url.substring(0, url.length - 1));
	}
	
	//关闭Loading
	closeLoadingDiv();
}


/**
 * 上传素材图片并预览 
 * inputFileId	:	图片文件 
 * fileShowDiv	:	图片预览 
 */
var fuIndex = 0;
function selectImageFileToOss(inputFileId, fileShowDiv) {
	
	var materialType = FileType.IMAGE_V;
	//文件种类
	var suppotFormat = getFileSuffix(materialType);
	//校验文件合法性
	var fileObjs = document.getElementById(inputFileId).files[0];
	var fileName = fileObjs.name;
	//转换大小写
	var suffix = (fileName.substring(fileName.lastIndexOf(".")+1,fileName.length)).toLowerCase(); 
	if (suppotFormat.indexOf(suffix) == -1) {
		Utils.showCustomTips(inputFileId, 1, '文件格式错误，支持的格式为：' + suppotFormat, '#000', '#ffe74c', 5);
		fileObjs.outerHTML = fileObjs.outerHTML; 
		return false;
	}
	
	var isOk = checkUploadFileSize(materialType, getFileSizeMByB(fileObjs.size))
	if(!isOk){
		Utils.showCustomTips(inputFileId, 1, "文件超出限制大小(" + getMaxFileSizeDes() + ")，请按系统要求上传!", '#000', '#ffe74c', 5);
		return false;
	}
	createLoadingDiv();
	
	fuIndex++;
	
	// 初始化预览数据
	getImgPreHtml(inputFileId,fuIndex,fileShowDiv,false,suffix, null);
	
	// 获取请求参数
	var client = getOssWrapper();
	// 执行请求
	client.multipartUpload(getStoreAs(fileObjs), fileObjs,{
		progress: function* (percent, cpt) {  
			percent =  Utils.toFormatDecimal(percent*100,0);
			setFileProgress(percent, fuIndex);
		}
	}).then(function (result) {
		var fileUrl = handleOssUrl(result.res.requestUrls[0]);
		$("#"+inputFileId).attr("data-url",fileUrl);
		$(".materialUrl_"+fuIndex).attr("src",fileUrl);
		closeLoadingDiv();
	}).catch(function (err) {
		closeLoadingDiv();
	});
}

/**
 * 初始化预览数据
 * 
 * @param inputFileId 文件标示
 * @param fuIndex 下标
 * @param fileShowDiv 显示位置
 * @param isUpComplete 是否编辑时
 * @param imgUrl URL
 * @returns
 */
function getImgPreHtml(inputFileId,fuIndex,fileShowDiv,isUpComplete,suffix,imgUrl){
	// 初始化、进度条(默认隐藏)、文件名
	var fileDiv = "";
    fileDiv += "	<div class='fileItem file-item fl' data-del-id='"+inputFileId+"' data-index='"+fuIndex+"'>";
    fileDiv += "		<div class='item-img'>";
    if(Utils.isNull(imgUrl)){
    	fileDiv += "			<img class='materialUrl_"+fuIndex+"' src=\"image/fileLogo/"+suffix+".jpg\" />";
    }else{
    	fileDiv += "			<img class='materialUrl_"+fuIndex+"' src=\""+imgUrl+"\" />";
    }
    fileDiv += "		</div>";
    if(!isUpComplete){
	    fileDiv += "		<div class='progress'>";
	    fileDiv += "			<div class='solidBar fileProgress_"+fuIndex+"' style='width:100%' ></div>";
	    fileDiv += "			<div class='progressTit fileProgressTit_"+fuIndex+"'>待上传...</div>";
	    fileDiv += "		</div>";
    }
    fileDiv += "	</div>";
    $("#"+fileShowDiv).html(fileDiv);
}

function uploadEditorImage(fileObjs,insert) {
	var url = "";
	var html = "";
	var formdata = new FormData();
	formdata.append("dataFile", fileObjs[0]);
	formdata.append("fileType", FileType.IMAGE_V);
	$.ajax({
		type : 'POST',
		url : 'file/uploadFile',
		data : formdata,
		dataType : "json",
//			async : false,
		cache : false,
		contentType : false,
		processData : false,
		beforeSend : function() {
			//创建LoadingDiv
			createLoadingDiv();
		},
		success : function(response) {
			if (response.code == 0) {
				insert(response.data.url);
			} else {
				showAlert(response.message);
			}
		},
		error : function(data) {
			//关闭LoadingDiv
			closeLoadingDiv();
			showAlert(fileList[i]+"上传失败!");
		}, 
		complete : function() {
			//关闭LoadingDiv
			closeLoadingDiv();
		}
	});
	return false;
}

/**
 * 显示文件
 */
function openUploadFileUrl(imageUrl){
	var httpHead = imageUrl.substr(0,5).toLowerCase(); 
	if(httpHead!="https" && httpHead!="http:"){
		imageUrl = "http://" + $imageUrl;
	}
	if(Utils.isNotNull(imageUrl)){
		window.open(imageUrl, "", "fullscreen=1");
	}
}  

/**
 * 填充文件 div
 */
function fillFileDiv(url ,type){
	if( url == null ){
		return "";
	}
	
	var trHtml = "";
	if(type == FileType.IMAGE_V){
		url = url + Global.IMG_SiZE_TWO_H;
		trHtml = '<a title="显示" href=\'' + url + '\' target="_blank"><img src=\'' + url + '\' /></a>'; 
	}else if(type == FileType.VIDEO_V || type == FileType.AUDIO_V){
		trHtml += "<img src='image/video_img.jpg' style='width: 200px;' alt='' />";
		trHtml += "<div class='tools tools-top'>" ;
		trHtml += "<a title='显示' href='javascript:openUploadFileUrl(\"" + url + "\");'> <i class='icon-link'></i></a>";
		trHtml += "</div>";
	}
	return trHtml;
}